<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Download, Delete } from '@element-plus/icons-vue';
import { WaybillService, type WaybillData, type WaybillQueryParams } from '@/services/waybillService';

// 表格数据
const tableData = ref<WaybillData[]>([]);
const loading = ref(false);

// 选中的行
const selectedRows = ref<WaybillData[]>([]);

// 处理多选
const handleSelectionChange = (selection: WaybillData[]) => {
  selectedRows.value = selection;
};

// 查看详情
const handleViewDetail = (row: WaybillData) => {
  console.log('查看详情', row);
  ElMessage.info(`查看运单 ${row.waybillNo} 详情`);
  // TODO: 这里应该跳转到运单详情页面
};

// 打印运单
const handlePrint = (row: WaybillData) => {
  ElMessage.success(`运单 ${row.waybillNo} 已开始打印`);
};

// 取消运单
const handleCancelWaybill = async (row: WaybillData) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消运单 ${row.waybillNo} 吗？`,
      '取消运单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const result = await WaybillService.cancelWaybill(row.objectId!, '用户主动取消');
    
    if (result.success) {
      ElMessage.success('运单已取消');
      loadData();
    } else {
      ElMessage.error('取消运单失败');
    }
  } catch (error) {
    // 用户取消操作或其他错误
  }
};

// 确认发车
const handleConfirmDeparture = async (row: WaybillData) => {
  try {
    await ElMessageBox.confirm(
      `确定要确认发车运单 ${row.waybillNo} 吗？`,
      '确认发车',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const result = await WaybillService.confirmDeparture(row.objectId!);
    
    if (result.success) {
      ElMessage.success('已确认发车');
      loadData();
    } else {
      ElMessage.error('确认发车失败');
    }
  } catch (error) {
    // 用户取消操作或其他错误
  }
};

// 搜索关键词
const searchVehicleNo = ref('');
const searchWaybillNo = ref('');
const searchDriverPhone = ref('');

// 发货站点选择
const departureStation = ref('');
const departureStationOptions = [
  { label: '义乌站', value: '义乌站' },
  { label: '北京站', value: '北京站' },
  { label: '上海站', value: '上海站' },
  { label: '广州站', value: '广州站' }
];

// 到达站点选择
const destinationStation = ref('');
const destinationStationOptions = [
  { label: '河北站', value: '河北站' },
  { label: '山东站', value: '山东站' },
  { label: '江苏站', value: '江苏站' },
  { label: '浙江站', value: '浙江站' }
];

// 中转站点选择
const transferStation = ref('');
const transferStationOptions = [
  { label: '天津站', value: '天津站' },
  { label: '郑州站', value: '郑州站' },
  { label: '武汉站', value: '武汉站' },
  { label: '西安站', value: '西安站' }
];

// 配载日期范围
const assignDateRange = ref([]);

// 状态选择
const waybillStatus = ref('');
const statusOptions = [
  { label: '全部', value: '' },
  { label: '已配载', value: '1' },
  { label: '已发车', value: '2' },
  { label: '运输中', value: '3' },
  { label: '已送达', value: '4' }
];

// 加载数据方法
const loadData = async () => {
  loading.value = true;
  try {
    const params: WaybillQueryParams = {
      vehiclePlate: searchVehicleNo.value,
      waybillNo: searchWaybillNo.value,
      driverPhone: searchDriverPhone.value,
      status: waybillStatus.value ? parseInt(waybillStatus.value) : undefined,
      startDate: assignDateRange.value[0],
      endDate: assignDateRange.value[1],
      page: currentPage.value,
      pageSize: pageSize.value
    };

    const result = await WaybillService.getAssignedWaybills(params);
    
    if (result.success) {
      tableData.value = result.data;
      total.value = result.total;
    } else {
      ElMessage.error('获取数据失败');
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    ElMessage.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (date: Date | string): string => {
  if (!date) return '';
  const d = new Date(date);
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 执行搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadData();
};

// 重置搜索条件
const handleReset = () => {
  searchVehicleNo.value = '';
  searchWaybillNo.value = '';
  searchDriverPhone.value = '';
  departureStation.value = '';
  destinationStation.value = '';
  transferStation.value = '';
  waybillStatus.value = '';
  assignDateRange.value = [];
  currentPage.value = 1;
  loadData();
};

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadData();
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadData();
};

// 导出
const handleExport = () => {
  ElMessage.success('运单数据导出成功');
};

// 组件初始化时加载数据
onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="waybill-assigned-container">
    <div class="search-form">
      <div class="search-form-row">
        <el-input v-model="searchVehicleNo" placeholder="请输入车牌号搜索" clearable>
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-input v-model="searchWaybillNo" placeholder="请输入运单号搜索" clearable>
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-input v-model="searchDriverPhone" placeholder="请输入司机电话搜索" clearable>
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select v-model="waybillStatus" placeholder="运单状态" clearable>
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      
      <div class="search-form-row">
        <el-select v-model="departureStation" placeholder="发货站" clearable>
          <el-option
            v-for="item in departureStationOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        
        <el-select v-model="destinationStation" placeholder="到达站" clearable>
          <el-option
            v-for="item in destinationStationOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        
        <el-select v-model="transferStation" placeholder="中转站" clearable>
          <el-option
            v-for="item in transferStationOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        
        <el-date-picker
          v-model="assignDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="配载开始日期"
          end-placeholder="配载结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
        
        <div class="button-group">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </div>
    </div>
    
    <div class="action-bar">
      <div class="left-actions">
        <el-button @click="handleExport">导出</el-button>
        <el-button :icon="Refresh" @click="loadData">刷新</el-button>
      </div>
      <div class="right-actions">
        <el-alert
          title="可左右滑动查看更多字段"
          type="info"
          :closable="false"
          show-icon
        />
      </div>
    </div>
    
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column label="货号" prop="cargoNo" width="120" fixed="left" />
        <el-table-column label="运单号" prop="waybillNo" width="120" fixed="left" />
        <el-table-column label="发货人" prop="senderName" width="100" />
        <el-table-column label="发货人电话" prop="senderPhone" width="120" />
        <el-table-column label="发货人地址" prop="senderAddress" min-width="200" show-overflow-tooltip />
        <el-table-column label="收货人" prop="receiverName" width="100" />
        <el-table-column label="收货人电话" prop="receiverPhone" width="120" />
        <el-table-column label="收货人地址" prop="receiverAddress" min-width="200" show-overflow-tooltip />
        <el-table-column label="货物类型" prop="cargoType" width="100" />
        <el-table-column label="总体积(方)" prop="totalVolume" width="120" />
        <el-table-column label="总重量(KG)" prop="totalWeight" width="120" />
        <el-table-column label="付款方式" width="100">
          <template #default="{ row }">
            {{ WaybillService.getPaymentMethodText(row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column label="声明价值" prop="declaredValue" width="100" />
        <el-table-column label="保费" prop="insuranceFee" width="100" />
        <el-table-column label="配送费" prop="deliveryFee" width="100" />
        <el-table-column label="卸货费" prop="unloadingFee" width="100" />
        <el-table-column label="总运费" prop="totalFreight" width="100" />
        <el-table-column label="司机" prop="driverId" width="100" />
        <el-table-column label="司机电话" prop="driverPhone" width="120" />
        <el-table-column label="车辆号牌" prop="vehiclePlate" width="120" />
        <el-table-column label="线路" prop="route" width="100" />
        <el-table-column label="配载时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.assignedTime) }}
          </template>
        </el-table-column>
        <el-table-column label="发车时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.departureTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" fixed="right">
          <template #default="{ row }">
            <el-tag 
              :type="
                row.status === 1 ? 'primary' :
                row.status === 2 ? 'success' :
                row.status === 3 ? 'warning' : 'info'
              "
            >
              {{ WaybillService.getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">详情</el-button>
            <el-button type="primary" link @click="handlePrint(row)">打印</el-button>
            <el-button 
              v-if="row.status === 1" 
              type="success" 
              link 
              @click="handleConfirmDeparture(row)"
            >
              确认发车
            </el-button>
            <el-button 
              v-if="row.status === 1" 
              type="danger" 
              link 
              @click="handleCancelWaybill(row)"
            >
              取消运单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="pagination-container">
      <div class="pagination-info">
        共 {{ total }} 条
      </div>
      <div class="pagination-size">
        <el-select v-model="pageSize" @change="handleSizeChange">
          <el-option :value="10" label="10条/页" />
          <el-option :value="20" label="20条/页" />
          <el-option :value="50" label="50条/页" />
          <el-option :value="100" label="100条/页" />
        </el-select>
      </div>
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
      />
      <div class="pagination-jump">
        前往 <el-input v-model="currentPage" type="number" size="small" style="width: 50px" /> 页
      </div>
    </div>
  </div>
</template>

<style scoped>
.waybill-assigned-container {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  width: 100%;
}

.search-form-row {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  width: 100%;
}

.search-form-row:last-child {
  margin-bottom: 0;
}

.search-form-row > * {
  flex: 1;
  min-width: 0;
}

.search-form-row .el-date-editor {
  flex: 1.5;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  min-width: 180px;
  flex: 0 0 auto;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  align-items: center;
}

.left-actions {
  display: flex;
  gap: 10px;
}

.right-actions {
  display: flex;
  align-items: center;
}

.right-actions .el-alert {
  padding: 8px 12px;
  margin: 0;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

.pagination-jump {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 14px;
}

.el-table {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
  width: 100%;
}
</style>